package com.android.duininsuoai.activity.mine;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.duininsuoai.R;
import com.android.duininsuoai.app.BaseActivity;
import com.android.duininsuoai.model.member.LoginResultData;
import com.android.duininsuoai.model.member.LoginResultDataCallback;
import com.android.duininsuoai.model.member.SendCodeData;
import com.android.duininsuoai.model.member.SendCodeDataCallback;
import com.android.duininsuoai.utils.ConstantsUrl;
import com.android.duininsuoai.utils.HttpUtils;
import com.android.duininsuoai.utils.MyLog;
import com.android.duininsuoai.utils.ObjectUtils;
import com.android.duininsuoai.view.dialog.MainMsg;
import com.elbbbird.android.socialsdk.SocialSDK;
import com.elbbbird.android.socialsdk.model.SocialToken;
import com.elbbbird.android.socialsdk.model.SocialUser;
import com.elbbbird.android.socialsdk.otto.SSOBusEvent;
import com.squareup.otto.Subscribe;
import com.tencent.connect.common.Constants;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class LoginActivity extends BaseActivity {


    public static LoginActivity intance = null;


    @BindView(R.id.progress_loading)
    FrameLayout progress;
    @BindView(R.id.main_top_register)
    TextView main_top_register;
    @BindView(R.id.login_radio_login)
    RadioButton loginRadioLogin;
    @BindView(R.id.login_radio_sign)
    RadioButton loginRadioSign;
    @BindView(R.id.login_radio_ll)
    RadioGroup loginRadioLl;
    @BindView(R.id.ll_login_phone)
    EditText llLoginPhone;
    @BindView(R.id.ll_login_pd)
    EditText llLoginPd;
    @BindView(R.id.ll_sign)
    LinearLayout ll_sign;
    @BindView(R.id.ll_login)
    LinearLayout llLogin;
    @BindView(R.id.ll_sign_phone)
    EditText llSignPhone;
    @BindView(R.id.ll_sign_code)
    EditText llSignCode;
    @BindView(R.id.ll_sign_code_send)
    TextView llSignCodeSend;
    @BindView(R.id.forget_ps_tv)
    TextView forget_ps_tv;
    @BindView(R.id.login_weixin)
    TextView login_weixin;
    @BindView(R.id.login_weibo)
    TextView login_weibo;
    @BindView(R.id.login_qq)
    TextView login_weiqq;
    @BindView(R.id.login)
    TextView login;
    private LoginActivity mcontext;
    private TimeCount time;
    private boolean networkConnected;
    private MainMsg mainMsg;
    private boolean isLogin=true;
    private String openId;
    private int type;
    private String nickname;
    private String avatar;
    private String unionid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        intance = this;
        mcontext = LoginActivity.this;
        ButterKnife.bind(this);
        initUI();
        time = new TimeCount(60000, 1000);
    }

    private void initUI() {

    }

    @Subscribe
    public void onOauthResult(SSOBusEvent event) {
        switch (event.getType()) {
            case SSOBusEvent.TYPE_GET_TOKEN:
//                mainMsg.close();
                progress.setVisibility(View.GONE);
                SocialToken token = event.getToken();
                MyLog.e("登录成功", "获取openid " + token.getOpenId());
                break;
            case SSOBusEvent.TYPE_GET_USER:
//                mainMsg.close();
                progress.setVisibility(View.GONE);
                SocialUser user = event.getUser();
                MyLog.e("登录成功", "获取getUnionid " + user.getUnionid());
                MyLog.e("登录成功", "获取头像 " + user.getAvatar());
                openId = user.getToken().getOpenId();
                type = user.getType();
                nickname = user.getName();
                avatar = user.getAvatar();
                unionid = user.getUnionid();
                setLoginThree(openId, type, nickname, avatar, unionid);
                break;
            case SSOBusEvent.TYPE_FAILURE:
//                mainMsg.close();
                progress.setVisibility(View.GONE);
                Exception e = event.getException();
                MyLog.e("登录失败", "登录失败" + e.toString());
                break;
            case SSOBusEvent.TYPE_CANCEL:
//                mainMsg.close();
                progress.setVisibility(View.GONE);
                MyLog.e("取消登录", "取消登录");
                break;
        }
    }


    //登录
    private void setLoginThree(final String openid, final int type, String nickname, String avatar, String unionid) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORSENDTHREELOGIN;
        HashMap<String, String> map = new HashMap<>();
        String typename = "";
        switch (type) {
            case 1:
                typename = "wb";
                break;
            case 2:
                typename = "wx";
                break;
            case 3:
                typename = "qq";
                break;

        }
        map.put("openid", openid);
        map.put("type", typename);
        map.put("nickname", nickname);
        map.put("avatar", avatar);
        map.put("unionid", unionid);
        MyLog.e("openid", openid);
        MyLog.e("type", typename);
        MyLog.e("nickname", nickname);
        MyLog.e("unionid", unionid);
        MyLog.e("avatar", avatar);
        if (networkConnected) {

            final String finalTypename = typename;
            HttpUtils.post(address, null, map, new LoginResultDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    progress.setVisibility(View.GONE);
                }

                @Override
                public void onResponse(LoginResultData response, int id) {

                    progress.setVisibility(View.GONE);

                    if (response.getCode() == 0 && response.getData()!=null) {
                        LoginResultData.DataBean data = response.getData();
                        if(TextUtils.isEmpty(data.getUID())){
                            Intent intentsign = new Intent(mcontext, SignActivity.class);
                            intentsign.putExtra("openid", openid);
                            intentsign.putExtra("type", finalTypename);
                            startActivityForResult(intentsign,1);
                        }else {
                            PostLoginThree(data.getUNAME(), data.getAvatar(), data.getUID(), data.getUPSW(), type, data.getTOKEN());
                        }
                    } else {
                        ObjectUtils.toast(mcontext, response.getMsg());
                    }
                }
            });

        } else {
            progress.setVisibility(View.GONE);
            ObjectUtils.toast(mcontext, "网络连接出错了");
        }

    }
    //登录并保存
    private void PostLoginTwo(String uname, String avatar, String uid, String upsw,String token) {
        SharedPreferences sp = getSharedPreferences(ConstantsUrl.USERDATA, 0);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(ConstantsUrl.USERDATA_NAME, uname);
        edit.putString(ConstantsUrl.USERDATA_AVATAR, avatar);
        edit.putString(ConstantsUrl.USERDATA_UID, uid);
        edit.putString(ConstantsUrl.USERDATA_UPSW, upsw);
        edit.putString(ConstantsUrl.USERDATA_TOKEN, token);
        edit.putInt(ConstantsUrl.USERDATA_TYPE, 0);
        edit.commit();
        ObjectUtils.toast(LoginActivity.this, "登录成功");
        LoginActivity.intance.finish();

        finish();
    }
    //登录并保存
    private void PostLoginThree(String uname, String avatar, String uid, String upsw, int type,String token) {
        SharedPreferences sp = getSharedPreferences(ConstantsUrl.USERDATA, 0);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(ConstantsUrl.USERDATA_NAME, uname);
        edit.putString(ConstantsUrl.USERDATA_AVATAR, avatar);
        edit.putString(ConstantsUrl.USERDATA_UID, uid);
        edit.putString(ConstantsUrl.USERDATA_UPSW, upsw);
        edit.putString(ConstantsUrl.USERDATA_TOKEN, token);
        edit.putInt(ConstantsUrl.USERDATA_TYPE, type);
        edit.commit();
        ObjectUtils.toast(mcontext, "登录成功");
        LoginActivity.intance.finish();
        finish();
    }


    @Override
    protected void onStart() {
        super.onStart();
        progress.setVisibility(View.GONE);
    }


        @OnClick({R.id.main_top_back,R.id.main_top_register,R.id.forget_ps_tv,R.id.ll_sign,R.id.ll_login,R.id.login_radio_login
                ,R.id.login_radio_sign,R.id.login
        ,R.id.ll_sign_code_send,R.id.login_weixin,R.id.login_qq,R.id.login_weibo})
            public void onClick(View view) {
         switch (view.getId()) {
             case R.id.main_top_back:
                 finish();
                 break;
             case  R.id.login_weixin:
                 progress.setVisibility(View.VISIBLE);
                 SocialSDK.setDebugMode(true);
                 SocialSDK.initWeChat(ConstantsUrl.WX_APPID, ConstantsUrl.WX_SERCET);
                 SocialSDK.oauthWeChat(mcontext);
                 break;
             case R.id.login_qq:
                 progress.setVisibility(View.VISIBLE);
                 SocialSDK.setDebugMode(true);
                 SocialSDK.initQQ(ConstantsUrl.QQ_APPID);
                 SocialSDK.oauthQQ(mcontext);
                 break;
             case R.id.login_weibo:
                 SocialSDK.setDebugMode(true);
                 SocialSDK.initWeibo(ConstantsUrl.SINA_WB_APPKEY);
                 SocialSDK.oauthWeibo(mcontext);
                 break;
            case R.id.main_top_register:
                Intent intentsign = new Intent(this, SignActivity.class);
                startActivity(intentsign);
                finish();
                break;
            case R.id.forget_ps_tv:
                Intent forget_ps_tvintent = new Intent(this,FindPwActivity.class);
                startActivity(forget_ps_tvintent);
                break;
             case R.id.login_radio_sign:
                 loginRadioSign.setChecked(true);
                 loginRadioLogin.setChecked(false);
                 MyLog.e("dsf","dfsf");
                 ll_sign.setVisibility(View.VISIBLE);
                 llLogin.setVisibility(View.GONE);
                 isLogin=false;
                 break;
             case R.id.login_radio_login:
                 loginRadioSign.setChecked(false);
                 loginRadioLogin.setChecked(true);
                 ll_sign.setVisibility(View.GONE);
                 llLogin.setVisibility(View.VISIBLE);
                 isLogin=true;
                 break;
             case R.id.ll_sign_code_send:
                 String sign_phone = llSignPhone.getText().toString().trim();
                 if ("".equals(sign_phone)) {
                     ObjectUtils.toast(this, "请输入手机号码");
                     return;
                 }
                 SendCode(sign_phone);
                 break;
             case R.id.login:

                  if(isLogin)
                  {
                      String lgph = llLoginPhone.getText().toString().trim();
                      String lgpd =  llLoginPd.getText().toString().trim();
                      if ("".equals(lgph)) {
                          ObjectUtils.toast(this, "请输入账号");
                          return;
                      }
                      if (!lgpd.equals(lgpd)) {
                          ObjectUtils.toast(this, "请输入密码");
                          return;
                      }
                      PostLogin(lgph,lgpd);
                  }
                 else
                  {
                      String sgphone = llSignPhone.getText().toString().trim();
                      String sgcode = llSignCode.getText().toString().trim();
                      if ("".equals(sgphone)) {
                          ObjectUtils.toast(this, "请输入手机号");
                          return;
                      }
                      if ("".equals(sgcode)) {
                          ObjectUtils.toast(this, "请输入验证码");
                          return;
                      }
                      PostLogin(sgphone,sgcode);
                  }
                 break;
        }
    }
    //发送验证码
    private void SendCode(String phone) {
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORSENDMESSAGE;
        HashMap<String, String> map = new HashMap<>();
        map.put("mobile", phone);
        map.put("act", "sms_code");
        networkConnected = ObjectUtils.isNetworkConnected(this);
        if (networkConnected) {

            HttpUtils.post(address, map, new SendCodeDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(SendCodeData response, int id) {

                    ObjectUtils.toast(LoginActivity.this, response.getMsg());
                    if (response.getCode() == 0) {
                        time.start();
                    }

                }
            });

        } else {

            ObjectUtils.toast(this, "网络连接出错了");
        }

    }
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            llSignCodeSend.setText("重新获取验证码");
            llSignCodeSend.setTextColor(Color.parseColor("#ffffff"));
            llSignCodeSend.setBackgroundResource(R.drawable.corner_red_bg);
            llSignCodeSend.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            llSignCodeSend.setClickable(false);// 防止重复点击
            llSignCodeSend.setTextColor(Color.parseColor("#5a5a5a"));
            llSignCodeSend.setBackgroundResource(R.drawable.corner_gray_bg);
            llSignCodeSend.setText("重新发送(" + millisUntilFinished / 1000 + ")秒");
        }
    }
    //登录
    private void PostLogin(String phone, String pd) {
        networkConnected = ObjectUtils.isNetworkConnected(this);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORLOGIN;
        HashMap<String, String> map = new HashMap<>();
        MyLog.e("地址", address);
        map.put("username", phone);
        map.put("password", pd);
        if (networkConnected) {
            HttpUtils.post(address, map, new LoginResultDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(LoginResultData response, int id) {
                    if (response.getCode() == 0) {
                        //保存用户数据
                        PostLoginTwo(response.getData().getUNAME(), response.getData().getAvatar(), response.getData().getUID(), response.getData().getUPSW(),response.getData().getTOKEN());
                    } else {
                        ObjectUtils.toast(LoginActivity.this, response.getMsg());
                    }

                }
            });

        } else {

            ObjectUtils.toast(this, "网络连接出错了");
        }

    }

//    @OnClick({R.id.weixin_login, R.id.else_login, R.id.back_login})
//    public void onClick(View view) {
//        switch (view.getId()) {
//            case R.id.weixin_login:
//                progress.setVisibility(View.VISIBLE);
//                SocialSDK.setDebugMode(true);
//                SocialSDK.initWeChat(ConstantsUrl.WX_APPID, ConstantsUrl.WX_SERCET);
//                SocialSDK.oauthWeChat(mcontext);
//                break;
//            case R.id.else_login:
//                mainMsg.show(mcontext.getWindow().getDecorView(), 6, null);
//                break;
//            case R.id.back_login:
//                finish();
//                break;
//        }
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SocialSDK.oauthWeiboCallback(mcontext, requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_LOGIN || requestCode == Constants.REQUEST_APPBAR) {
            SocialSDK.oauthQQCallback(requestCode, resultCode, data);
        }
        if(requestCode == 1){
            if(resultCode == 1 ){
                setLoginThree(openId, type, nickname, avatar, unionid);
            }else {
                if (type==1) {
                    SocialSDK.revokeWeibo(mcontext);
                } else if (type==2) {
                    SocialSDK.revokeWeChat(mcontext);
                } else if (type==3) {
                    SocialSDK.revokeQQ(mcontext);
                }
            }
        }

    }


}
